//
//  UITextView+Extension.swift
//  KVBestMicroblog
//
//  Created by 李康卫 on 16/8/1.
//  Copyright © 2016年 李康卫. All rights reserved.
//

import UIKit

extension UITextView {
    ///输入属性文本
     func insertEmoticon(emoticonModel: KVEmoticonModel) {
        if let emoji = emoticonModel.emoji {
            self.insertText(emoji)
        } else {
            
            //图片文本要用属性文本来显示
            let image = UIImage(named: emoticonModel.iconPath!)
            //创建附件添加图片文本附件
            let attachment = KVTextAttachment()
            attachment.image = image
            attachment.chs = emoticonModel.chs
            //定义一个属性用于网络传输，系统不能满足自定义一个分类
            
            //获取文本高度设置图片大小
            let imageWH = self.font?.lineHeight ?? 10
            attachment.bounds = CGRect(x: 0, y: -4, width: imageWH, height: imageWH)
            //创建属性文本
            let attributedText = NSAttributedString(attachment: attachment)
            //要设置font
            let attributedTextM = NSMutableAttributedString(attributedString: attributedText)
            //添加font属性
            
            // MARK: -  error错误
            attributedTextM.addAttribute(NSFontAttributeName, value: self.font ?? 10, range: NSRange(location: 0, length: 1))
            
            //获取当前textView的文本插入输入的图片文本
            let currentAttributedText = NSMutableAttributedString(attributedString: (self.attributedText)!)
            //获取光标位置进行插入
            let selectedRange = self.selectedRange
            currentAttributedText.replaceCharactersInRange(selectedRange, withAttributedString: attributedTextM)
            
            //给textVIew赋值
            self.attributedText = currentAttributedText
            //从新设置光标的位置
            self.selectedRange = NSRange(location: (selectedRange.location + 1), length: 0)
            // MARK: -手动发送TextView改变的通知
            NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: self)
            self.delegate?.textViewDidChange!(self)
        }
        //选中的表情还要添加到最近
        KVEmoticonModelManeger.sharedEmoticonManeger.addRecentEmoticon(emoticonModel)
    }
    ///输出属性文本
    func outputContentText() -> String{
        //截取分段拼接
        var resultString: String = ""

        self.attributedText.enumerateAttributesInRange(NSRange(location: 0, length: self.attributedText.length), options: NSAttributedStringEnumerationOptions(rawValue: 0)) { (dict, range, _) -> Void in
            
            if let attchment = dict["NSAttachment"] as? KVTextAttachment{
                //出去网络传输的字段
                resultString += attchment.chs!
            } else {
                //是普通文本可以直接截取拼接
                let nsText = self.attributedText.string as NSString
                let textStr = nsText.substringWithRange(range)
                resultString += textStr
            }
        }
        return resultString
    }
}
